package com.tianjs.xdiamandgenerate;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

public class JsonUtil {
	
	public final static ObjectMapper objectMapper = new ObjectMapper();
	/**
	 * json字符串转化为对象
	 * @param json
	 * @return
	 */
	public static <T> T jsonStrToOject(String json,Class<T> clazz){
		
		T obj = null;
		try {
			obj = objectMapper.readValue(json, clazz);
		} catch (IOException e) {
			e.printStackTrace();
			obj = null;
		}
		return obj;
	}
	
	/**
	 * 对象转换为JSON
	 * @param obj
	 * @return
	 */
	public static String ObjectToJsonStr(Object obj){
		
		String jsonStr = null;
		try {
			jsonStr  = objectMapper.writeValueAsString(obj);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("请求对象转JSON失败,入参为非正常格式JSON对象");
		}
		return jsonStr;
	}
	
	public static <T> List<T> jsonToArrayList(String json,Class<T> clazz){
		List<T> list = null;
		JavaType javaType = objectMapper.getTypeFactory().constructParametricType(ArrayList.class, clazz); 
		try {
			list = objectMapper.readValue(json, javaType);
			return list;
		} catch (JsonParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}
	
}
